const regular = require("../../utils/regular.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    payForm: {
      timeStamp: "",
      nonceStr: "",
      prePayId: "",
      paySign: "",
    },
    payResult: "",
    errorMsg: ""
  },

  /**
   * 提交按钮事件
   */
  submitForm: function () {
    // 提交信息验证
    let timeStamp = this.data.payForm.timeStamp;
    let nonceStr = this.data.payForm.nonceStr;
    let prePayId = this.data.payForm.prePayId;
    let paySign = this.data.payForm.paySign;

    if (!timeStamp || timeStamp.length !== 10 || !regular.matchNumber(timeStamp)) {
      this.setData({ errorMsg: "timestamp参数填写不正确!" });
      return;
    }

    if (!nonceStr || nonceStr.length < 10 || nonceStr.length > 32 || !regular.matchWordAndNum(nonceStr)) {
      this.setData({ errorMsg: "nonceStr参数填写不正确!" });
      return;
    }

    if (!prePayId || prePayId.length < 30 || prePayId.length > 128) {
      this.setData({ errorMsg: "prePayId参数填写不正确!" });
      return;
    }

    if (!paySign || paySign.length < 64 || paySign.length > 512) {
      this.setData({ errorMsg: "paySign参数填写不正确!" });
      return;
    }

    const that = this;

    // 发起支付
    wx.requestPayment({
      "timeStamp": timeStamp,
      "nonceStr": nonceStr,
      "package": prePayId,
      "signType": "RSA",
      "paySign": paySign
    }).then(res => {
      that.setData({ payResult: res.errMsg })
    }).catch(err => {
      that.setData({ payResult: err.errMsg })
    })
  },

  /**
   * 粘贴按钮事件处理
   */
  pasteHandler: async function (ev) {
    const pasteType = ev.currentTarget.dataset.paste;
    let pasteData;

    await wx.getClipboardData().then((res) => {
      pasteData = res.data;
    }).catch(() => {
      wx.showToast({
        title: "无法获取剪贴板数据",
        icon: "error",
        mask: true
      });

      return;
    });

    switch (pasteType) {
      case "timeStamp": {
        this.setData({ ["payForm.timeStamp"]: pasteData })
        break;
      }
      case "nonceStr": {
        this.setData({ ["payForm.nonceStr"]: pasteData })
        break;
      }
      case "prePayId": {
        this.setData({ ["payForm.prePayId"]: pasteData })
        break;
      }
      case "paySign": {
        this.setData({ ["payForm.paySign"]: pasteData })
        break;
      }
      default: {
        break;
      }
    }
  }
})